import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Input, 
  Select, 
  Row, 
  Col,
  Spin,
  message
} from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';

const { Search } = Input;
const { Option } = Select;

const IssueListPage = () => {
  const [issues, setIssues] = useState([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: null,
    category: null,
    priority: null
  });
  const history = useHistory();

  // 获取问题列表
  const fetchIssues = async () => {
    setLoading(true);
    try {
      const params = {};
      if (filters.status) params.status = filters.status;
      if (filters.category) params.category = filters.category;
      if (filters.priority) params.priority = filters.priority;
      
      const response = await api.get('/issues', { params });
      setIssues(response.data);
    } catch (error) {
      console.error('获取问题列表失败:', error);
      message.error('获取问题列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchIssues();
  }, [filters]);

  const handleSearch = async (value) => {
    if (value) {
      setLoading(true);
      try {
        // 这里可以实现搜索功能
        // 暂时使用过滤本地数据的方式
        const response = await api.get('/issues');
        const filtered = response.data.filter(issue => 
          issue.title.includes(value) || issue.description.includes(value)
        );
        setIssues(filtered);
      } catch (error) {
        console.error('搜索问题失败:', error);
        message.error('搜索问题失败');
      } finally {
        setLoading(false);
      }
    } else {
      fetchIssues();
    }
  };

  const handleStatusChange = (value) => {
    setFilters({ ...filters, status: value });
  };

  const handleCategoryChange = (value) => {
    setFilters({ ...filters, category: value });
  };

  const handlePriorityChange = (value) => {
    setFilters({ ...filters, priority: value });
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <a onClick={() => history.push(`/issues/${record.id}`)}>{text}</a>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'customer' ? 'blue' : 'green'}>
          {type === 'customer' ? '客户问题' : '内部问题'}
        </Tag>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category'
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      render: (priority) => {
        const color = priority === 'high' ? 'red' : priority === 'medium' ? 'orange' : 'green';
        return <Tag color={color}>{priority === 'high' ? '高' : priority === 'medium' ? '中' : '低'}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          open: { text: '待处理', color: 'blue' },
          in_progress: { text: '处理中', color: 'orange' },
          resolved: { text: '已解决', color: 'green' },
          closed: { text: '已关闭', color: 'gray' },
          rejected: { text: '已驳回', color: 'red' }
        };
        const { text, color } = statusMap[status];
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '提交人',
      dataIndex: 'submitter',
      key: 'submitter'
    },
    {
      title: '处理人',
      dataIndex: 'assignee',
      key: 'assignee'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (created_at) => new Date(created_at).toLocaleString()
    }
  ];

  return (
    <div>
      <h2>问题列表</h2>
      
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Search 
            placeholder="搜索问题" 
            allowClear 
            onSearch={handleSearch}
            enterButton={<SearchOutlined />}
          />
        </Col>
        <Col span={4}>
          <Select 
            placeholder="状态" 
            style={{ width: '100%' }} 
            allowClear
            onChange={handleStatusChange}
          >
            <Option value="open">待处理</Option>
            <Option value="in_progress">处理中</Option>
            <Option value="resolved">已解决</Option>
            <Option value="closed">已关闭</Option>
          </Select>
        </Col>
        <Col span={4}>
          <Select 
            placeholder="分类" 
            style={{ width: '100%' }} 
            allowClear
            onChange={handleCategoryChange}
          >
            <Option value="hardware">硬件</Option>
            <Option value="software">软件</Option>
            <Option value="firmware">固件</Option>
          </Select>
        </Col>
        <Col span={4}>
          <Select 
            placeholder="优先级" 
            style={{ width: '100%' }} 
            allowClear
            onChange={handlePriorityChange}
          >
            <Option value="high">高</Option>
            <Option value="medium">中</Option>
            <Option value="low">低</Option>
          </Select>
        </Col>
        <Col span={6}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => history.push('/create-issue')}
            block
          >
            创建问题
          </Button>
        </Col>
      </Row>
      
      {loading ? (
        <Spin size="large" style={{ display: 'block', margin: '50px auto' }} />
      ) : (
        <Table
          columns={columns}
          dataSource={issues}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true
          }}
        />
      )}
    </div>
  );
};

export default IssueListPage;